//
//  SureOrderController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/20.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "SureOrderController.h"
#define knoAddressHeight 567
#define knoAddressServiceHeaderHight 374
#define khadAddressServiceheaderHight 283
#define knoYouHuiHeight 100
#define khadAddressHeight 476
#define khadYouHuiHeight 233
//untils
#import "UIColor+Hex.h"
#import "AppDelegate.h"
#import "RDVTabBarController.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
#import "FMDBManager.h"
#import "Global.h"
//view
#import "SureOrderHeaderView.h"
#import "SureOrderFooterView.h"
#import "SureOrderCell.h"
#import "UIImage+ColorToImage.h"
#import "LouCengPickerView.h"
//controllers
#import "WeiXinPayController.h"
#import "UserCenter_FeedbackAndSuggestionController.h"
#import "ManageReceivedAddressController.h"
#import "MyOrderDetail_rootController.h"
#import "SelectServiceTimeController.h"
#import "MyGoodsOrderDetailController.h"
//model
#import "ReceivedAddressModel.h"
#import "ReceivedAddressOBJECT.h"
#import "LouCengInfoModel.h"

#import "MTA.h"
@interface SureOrderController ()<UITableViewDelegate,UITableViewDataSource>
{
    SureOrderHeaderView *_headerView;
    BOOL _isHadDefaultReceivedAddress;//是否有默认地址
    NSString *_totalPrice;//总价格
}
@property(nonatomic, strong)NSMutableArray *receivedAddressArr;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)NSMutableArray *louCengInfoArr;//楼层信息名字和ID
@property(nonatomic, strong)UILabel *totalPriceLabel;//总价格
@property(nonatomic, strong)UIButton *submitOrder;//提交订单
@property(nonatomic, strong)UILabel *marklabel;
@property(nonatomic, strong)UILabel *qingJieJi;
@property(nonatomic, strong)UIButton *qingJieJiSeletedBtn;
@property(nonatomic, strong)NSString *orderNum;
@end

@implementation SureOrderController
@synthesize serviceDataSource = _serviceDataSource;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efeeee"];
    [self addBackNavItem];
    self.title =@"确认订单";
    _dataSource = [[NSMutableArray alloc]init];
    _receivedAddressArr = [[NSMutableArray alloc]init];
    _louCengInfoArr = [[NSMutableArray alloc]init];
    [self loadProductListData];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:YES];
    if (self.orderType == kproductSureOrder) {
        [_headerView resetMarkContent:self.markContent];
    } else if (self.orderType == kserviceSureorder) {
        [_headerView resetServiceDate:self.serviceTime];
    }
    if (_isHadDefaultReceivedAddress&&self.addressData.lINKNAME.length != 0) {//默认地址存在用户修改地址（把选中的地址信息带过来）
        [self requestReceivedAddressSuccessWithDataDic:self.addressData];
    }
    [_tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"确认订单"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"确认订单"];
}
#pragma mark -- request Data
//加载小区信息
- (void)loadXiaoQuDetailInfoData {
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *xiaoQuAndStoreModel = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:xiaoQuAndStoreModel.xiaoQuID forKey:@"COMMUNITYID"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"common/communityDetail" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                if ([[dataDic objectForKey:@"OBJECT"] count]!= 0) {
                    LouCengPickerView *pickView = [[LouCengPickerView alloc]initWithFrame:CGRectMake(0, weakSelf.view.bounds.size.height - 248, weakSelf.view.bounds.size.width, 248) withComponentContents:[[ManagerGlobeUntil sharedManager] modifiedServerXiaoQuInfoDatasoruce:[dataDic objectForKey:@"OBJECT"]]delegate:(id<LouCengPickerViewDelegate>)weakSelf];
                    [pickView showInView:weakSelf.view];
                    _headerView.detailAddressBtn.enabled = NO;
                }
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
        }
        
        
    } failure:^(bool isFailure) {
    }];
}
//显示商品数据
- (void)loadProductListData {
    CGFloat totalprice = 0;
    if (self.orderType == kproductSureOrder) {//商品订单
        XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
        self.dataSource =[[FMDBManager sharedManager]QueryIsChoosedDataWithShopID:[NSString stringISNull:mode.storeID]];
        for (NSDictionary *dataDic in self.dataSource) {
            totalprice +=[[dataDic objectForKey:@"SELLPRICE"] floatValue]*[[dataDic objectForKey:@"BUYNUM"] integerValue];
        }
    } else if(self.orderType == kserviceSureorder) {//服务订单
        if (self.serviceDataSource.count != 0) {
            self.dataSource = [self.serviceDataSource mutableCopy];
            totalprice = [[[self.dataSource firstObject] objectForKey:@"SELLPRICE"] floatValue];
        }
    }
    _totalPrice = [NSString stringWithFormat:@"%.2f",totalprice];
    if (self.dataSource.count != 0) {
         [self loadDefaultReceivedAddressData];
    }
   
}
//提交订单
- (void)loadSubmitOrderData {
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
    
    ReceivedAddressOBJECT *data = [self.receivedAddressArr firstObject];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    UserInfoModel *userInfoMode = [[ManagerGlobeUntil sharedManager] getUserInfo];
    XiaoQuAndStoreInfoModel *xiaoQuAndStoreModel = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:userInfoMode.token forKey:@"TOKEN"];
    NSString *adapteStr = @"";
    if (self.orderType == kproductSureOrder) {//商品订单
        adapteStr = @"order/save";
        [parameter setObject:xiaoQuAndStoreModel.storeID forKey:@"STOREID"];
        [parameter setObject:[self appendProductID] forKey:@"GOODSID"];
        [parameter setObject:[self appendProductCount] forKey:@"COUNT"];
        [parameter setObject:_headerView.sendProductType forKey:@"TAKETYPE"];
        
    } else if (self.orderType == kserviceSureorder) {//服务订单
        NSDictionary *dataDic = [self.dataSource firstObject];
        if (self.homeMakeType.length ==0){
        adapteStr = @"service/order/save";
        [parameter setObject:xiaoQuAndStoreModel.storeID forKey:@"STOREID"];
        [parameter setObject:[dataDic objectForKey:@"SERVICESID"] forKey:@"SERVICESID"];
        
         }else if(self.homeMakeType.length !=0){
            adapteStr = @"ser/order/save";
             [parameter setObject:xiaoQuAndStoreModel.storeID forKey:@"STOREID"];
             [parameter setObject:xiaoQuAndStoreModel.storeName forKey:@"STORENAME"];
             [parameter setObject:self.homeMakeType forKey:@"TYPE"];
//             [parameter setObject:model.userName forKey:@"USERNAME"];
             [parameter setObject:[dataDic objectForKey:@"HOUR"] forKey:@"TOTALTIME"];
             [parameter setObject:[dataDic objectForKey:@"TITLE"] forKey:@"TITLE"];
             [parameter setObject:[dataDic objectForKey:@"SELLPRICE"] forKey:@"UNITPRICE"];
             [parameter setObject:[dataDic objectForKey:@"COUNT"] forKey:@"COUNT"];
        }
       [parameter setObject:self.serviceTime forKey:@"SERTIME"];


    }
    [parameter setObject:[NSString stringISNull:self.markContent] forKey:@"DESCRIBE"];
    [parameter setObject:_totalPrice.length == 0 ? @"" : _totalPrice forKey:@"AMOUNT"];
    [parameter setObject:_headerView.payType forKey:@"PAYTYPE"];
    if (_isHadDefaultReceivedAddress) {//有地址
        [parameter setObject:[NSString stringISNull:data.lINKNAME] forKey:@"LINKNAME"];
        NSString *sexStr = @"";
        if (data.sEX == 1) {
            sexStr = @"男";
        } else {
            sexStr = @"女";
        }
        [parameter setObject:sexStr forKey:@"SEX"];
        [parameter setObject:[NSString stringISNull:data.tEL] forKey:@"TEL"];
        NSString *address = [NSString stringWithFormat:@"%@",[NSString stringISNull:data.aDDRESS]];
        [parameter setObject:address forKey:@"ADDRESS"];
    } else {//无地址
        NSString *sexStr = @"";
        if ([_headerView.sexType isEqualToString:@"1"]) {
            sexStr = @"男";
        } else if([_headerView.sexType isEqualToString:@"2"]){
            sexStr = @"女";
        }
        [parameter setObject:sexStr forKey:@"SEX"];
        [parameter setObject:_headerView.userNameTextField.text forKey:@"LINKNAME"];
        [parameter setObject:_headerView.userTelePhoneTextField.text forKey:@"TEL"];
        [parameter setObject:_headerView.userAddressTextField.text forKey:@"ADDRESS"];
    }
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:adapteStr success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
             weakSelf.orderNum = [NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"ORDERNUM"]];
                if ([_headerView.payType isEqualToString:@"1"]) {//在线支付
                     [self submitOrderSucessWitOrderNumber:self.orderNum];
                } else if ([_headerView.payType isEqualToString:@"2"]) {//货到付款
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜您下单成功~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    alert.tag=1;
                    [alert show];
                }
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }

        }
    } failure:^(bool isFailure) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        
    }];

}

//获取默认收货地址信息
- (void)loadDefaultReceivedAddressData {
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    UserInfoModel *model = [[ManagerGlobeUntil sharedManager] getUserInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:model.token forKey:@"TOKEN"];
    [parameter setObject:serviceVersionNumber forKey:@"APIVERSION"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"user/defaultAddress" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            ReceivedAddressModel *model = [ReceivedAddressModel modelObjectWithDictionary:responseObject];
            NSString *state = [NSString stringTransformObject:model.sTATE];//状态码
            [weakSelf.receivedAddressArr removeAllObjects];
            if ([state isEqualToString:@"0"]) {//请求成功
                if (model.oBJECT.count != 0) {
                    [weakSelf.receivedAddressArr addObjectsFromArray:model.oBJECT];
                    _isHadDefaultReceivedAddress = YES;
                } else {
                    _isHadDefaultReceivedAddress = NO;
                }
                
            }else {//请求失败
                //[[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:self.view];
            }
            [weakSelf setupSubview];
            [weakSelf requestReceivedAddressSuccessWithDataDic:[weakSelf.receivedAddressArr firstObject]];
        }
    } failure:^(bool isFailure) {
        
    }];
}

//添加收货地址
- (void)loadAddReceivedAddressDataWithOrderNumber:(NSString*)orderNumber {//当用户无收货地址，生成订单，然后添加地址
    /*SIGNATURE:设备识别码
     TOKEN:用户签名
     LINKNAME:昵称
     TEL:联系电话，座机或手机
     SEX:性别1：男，2：女
     COMMUNITYID:社区ID
     BUILDID: 楼号ID
     UNITID:单元号ID
     ROOMID:房间门牌号ID
     ISDEFAULT:是否默认 1：是，0：否
     */

    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    UserInfoModel *userInfoMode = [[ManagerGlobeUntil sharedManager] getUserInfo];
    XiaoQuAndStoreInfoModel *xiaoQuAndStoreModel = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:xiaoQuAndStoreModel.storeID forKey:@"STOREID"];
    [parameter setObject:userInfoMode.token forKey:@"TOKEN"];
    [parameter setObject:_headerView.sexType forKey:@"SEX"];
    [parameter setObject:_headerView.userNameTextField.text forKey:@"LINKNAME"];
    [parameter setObject:_headerView.userTelePhoneTextField.text forKey:@"TEL"];
    [parameter setObject:_headerView.userAddressTextField.text forKey:@"ADDRESS"];
    [parameter setObject:serviceVersionNumber forKey:@"APIVERSION"];
    
    [parameter setObject:[NSNumber numberWithInteger:1] forKey:@"ISDEFAULT"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"user/addAddress" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            // NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                
                
            }else {//请求失败
                //[[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:self.view];
            }
            if ([_headerView.payType isEqualToString:@"1"]) {//在线支付
                WeiXinPayController *weiXinPayVC = [[WeiXinPayController alloc]init];
                weiXinPayVC.totalPrice = [NSString stringWithFormat:@"%@",_totalPrice];
                weiXinPayVC.orderNum = orderNumber;
                weiXinPayVC.homeMakeType =weakSelf.homeMakeType;
                if (weakSelf.orderType==kproductSureOrder) { //requestDataType  商品订单 是1 服务订单是 0
                    weiXinPayVC.requestDataType=@"1";
                }else if(weakSelf.orderType==kserviceSureorder)
                {
                    weiXinPayVC.requestDataType=@"0";
                }
                weiXinPayVC.goodIDs=weakSelf.orderType==kproductSureOrder?[weakSelf appendProductID]:@"";
                [weakSelf.navigationController pushViewController:weiXinPayVC animated:YES];
            } else if ([_headerView.payType isEqualToString:@"2"]) {//货到付款
               
                if (weakSelf.orderType==kproductSureOrder) { //requestDataType  商品订单 是1 服务订单是 0
                     MyGoodsOrderDetailController *goodOrderDetailVc=[[MyGoodsOrderDetailController alloc]init];
                    goodOrderDetailVc.orderNum =orderNumber;
                    [weakSelf.navigationController pushViewController:goodOrderDetailVc animated:YES];
                }else if(weakSelf.orderType==kserviceSureorder)
                {
                    MyOrderDetail_rootController *orderDetailVC = [[MyOrderDetail_rootController alloc]init];
                    orderDetailVC.orderNum = orderNumber;
                    orderDetailVC.currentIndexOfController = 0;
                    orderDetailVC.oldIndexOfController = 1;
                    orderDetailVC.requestDataType=@"0";
                    orderDetailVC.homeMakeType =weakSelf.homeMakeType;
                    orderDetailVC.selectedItemIndex = 0;
                    [weakSelf.navigationController pushViewController:orderDetailVC animated:YES];
                }
                
               
            }

        }
       
        
    } failure:^(bool isFailure) {
        if ([_headerView.payType isEqualToString:@"1"]) {//在线支付
            WeiXinPayController *weiXinPayVC = [[WeiXinPayController alloc]init];
            weiXinPayVC.totalPrice = [NSString stringWithFormat:@"%@",_totalPrice];
            weiXinPayVC.orderNum = orderNumber;
            weiXinPayVC.homeMakeType =weakSelf.homeMakeType;
            if (weakSelf.orderType==kproductSureOrder) { //requestDataType  商品订单 是1 服务订单是 0
                weiXinPayVC.requestDataType=@"1";
            }else if(weakSelf.orderType==kserviceSureorder)
            {
                weiXinPayVC.requestDataType=@"0";
            }
            weiXinPayVC.goodIDs=weakSelf.orderType==kproductSureOrder?[weakSelf appendProductID]:@"";
            [weakSelf.navigationController pushViewController:weiXinPayVC animated:YES];
        } else if ([_headerView.payType isEqualToString:@"2"]) {//货到付款
            
            if (weakSelf.orderType==kproductSureOrder) { //requestDataType  商品订单 是1 服务订单是 0
                MyGoodsOrderDetailController *goodOrderDetailVc=[[MyGoodsOrderDetailController alloc]init];
                goodOrderDetailVc.orderNum =orderNumber;
                [weakSelf.navigationController pushViewController:goodOrderDetailVc animated:YES];
            }else if(weakSelf.orderType==kserviceSureorder)
            {
                MyOrderDetail_rootController *orderDetailVC = [[MyOrderDetail_rootController alloc]init];
                orderDetailVC.orderNum = orderNumber;
                orderDetailVC.currentIndexOfController = 0;
                orderDetailVC.oldIndexOfController = 1;

                orderDetailVC.homeMakeType =weakSelf.homeMakeType;
                orderDetailVC.requestDataType=@"0";
                orderDetailVC.selectedItemIndex = 0;
                [weakSelf.navigationController pushViewController:orderDetailVC animated:YES];
            }

           
        }
        
    }];
}
- (void)requestReceivedAddressSuccessWithDataDic:(ReceivedAddressOBJECT*)data {
    NSString *address = [NSString stringWithFormat:@"%@",[NSString stringTransformObject:data.aDDRESS]];
    [_headerView updataWithName:[NSString stringTransformObject:data.lINKNAME]
                      telNumber:[NSString stringTransformObject:data.tEL]
                        address:address];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag ==1){//取消订单
        if (buttonIndex == 0){
            [self submitOrderSucessWitOrderNumber:self.orderNum];
        }
    }
}
- (void)submitOrderSucessWitOrderNumber:(NSString*)orderNumber {
    if (self.orderType == kproductSureOrder) {
        [self deleteDataWithFMDBShoppingCat];
    }
    if ([_headerView.payType isEqualToString:@"1"]) {//在线支付
        if (_isHadDefaultReceivedAddress) {//有地址
            
            WeiXinPayController *weiXinPayVC = [[WeiXinPayController alloc]init];
            weiXinPayVC.totalPrice = [NSString stringWithFormat:@"%@",_totalPrice];
            weiXinPayVC.orderNum = orderNumber;
            if (self.orderType==kproductSureOrder) { //requestDataType  商品订单 是1 服务订单是 0
                weiXinPayVC.requestDataType=@"1";
            }else if(self.orderType==kserviceSureorder)
            {
                weiXinPayVC.requestDataType=@"0";
            }
            weiXinPayVC.goodIDs=self.orderType==kproductSureOrder?[self appendProductID]:@"";
            weiXinPayVC.homeMakeType =self.homeMakeType;
            [self.navigationController pushViewController:weiXinPayVC animated:YES];
        } else {//无地址
            [self loadAddReceivedAddressDataWithOrderNumber:orderNumber];
        }
    } else if ([_headerView.payType isEqualToString:@"2"]) {//货到付款
        if (_isHadDefaultReceivedAddress) {//有地址
          
            if (self.orderType==kproductSureOrder) { //requestDataType  商品订单 是1 服务订单是 0
                MyGoodsOrderDetailController *goodOrderDetailVc=[[MyGoodsOrderDetailController alloc]init];
                goodOrderDetailVc.orderNum =orderNumber;
                [self.navigationController pushViewController:goodOrderDetailVc animated:YES];
            }else if(self.orderType==kserviceSureorder) 
            {
                MyOrderDetail_rootController *orderDetailVC = [[MyOrderDetail_rootController alloc]init];
                orderDetailVC.orderNum = orderNumber;
                orderDetailVC.currentIndexOfController = 0;
                orderDetailVC.oldIndexOfController = 1;
                orderDetailVC.homeMakeType =self.homeMakeType;
                orderDetailVC.requestDataType=@"0";
                orderDetailVC.selectedItemIndex = 0;
                [self.navigationController pushViewController:orderDetailVC animated:YES];

            }
                    } else {//无地址
            [self loadAddReceivedAddressDataWithOrderNumber:orderNumber];
        }
       
    }

}
-(void)deleteDataWithFMDBShoppingCat
{
    NSMutableArray * goodIDs=[NSMutableArray arrayWithArray:[[self appendProductID] componentsSeparatedByString:@","]];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    for (NSInteger i=0;i<goodIDs.count; i++) {
        [[FMDBManager sharedManager]deleteOneDataWithShopID:[NSString stringISNull:mode.storeID] goodID:[goodIDs objectAtIndex:i] ];
    }
}
#pragma mark -- 拼接商品ID 和数量
- (NSString*)appendProductID {
    NSMutableArray *idArr = [[NSMutableArray alloc]init];
    for (NSDictionary *dataDic in self.dataSource) {
        [idArr addObject:[dataDic objectForKey:@"ID"]];
    }
    return [idArr componentsJoinedByString:@","];
}

- (NSString*)appendProductCount {
    NSMutableArray *countArr = [[NSMutableArray alloc]init];
    for (NSDictionary *dataDic in self.dataSource) {
        [countArr addObject:[dataDic objectForKey:@"BUYNUM"]];
    }
    return [countArr componentsJoinedByString:@","];
}
#pragma mark -- UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.orderType == kserviceSureorder) {
       return 1;
        
    } else{
        return self.dataSource.count;
    }

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    if (self.orderType == kserviceSureorder) {
//        if ([self.homeMakeType isEqualToString:@"1"]) {
//             return self.dataSource.count+2;
//        }else {
//            return self.dataSource.count+1;
//        }
        return self.dataSource.count+1;
    } else{
        return 1;
    }
//    return self.dataSource.count;

}
-(void)buttonClick:(UIButton*)sender
{
    UIButton *button =(UIButton *)sender;
     _qingJieJiSeletedBtn.selected = !button.selected;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.orderType==kserviceSureorder) {
//        if(indexPath.section ==2)//清洁剂
//        {
//            static NSString *cellIdentifier = @"qingjieji";
//            
//            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//            if (cell == nil) {
//                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
//                cell.selectionStyle = UITableViewCellSelectionStyleNone;
//                _qingJieJi = [[UILabel alloc]initWithFrame:CGRectMake(VIEW_WIDTH/4, 0, VIEW_WIDTH/2+30, 44)];
//                [cell.contentView addSubview:_qingJieJi];
//                 _qingJieJiSeletedBtn=[[UIButton alloc]initWithFrame:CGRectMake(VIEW_WIDTH-42, 2, 40, 40)];
//                [cell.contentView addSubview:_qingJieJiSeletedBtn];
//
//            }
//            _qingJieJi.textAlignment =NSTextAlignmentRight;
//            _qingJieJi.font = [UIFont systemFontOfSize:13];
//            _qingJieJi.textColor=[UIColor colorWithHexString:@"#999999"];
//            _qingJieJi.text=@"大实惠提供清洁剂(+5/小时)";
//            cell.textLabel.text=@"清洁剂：";
//            cell.textLabel.numberOfLines=1;
//            cell.textLabel.font=[UIFont systemFontOfSize:15];
//           
//            UIImage *seletedimage=[UIImage imageNamed:@"checkBoxSelectdImage"];
//            UIImage *normalimage=[UIImage imageNamed:@"checkBoxNormalImage"];
//            [_qingJieJiSeletedBtn setImage:normalimage forState:UIControlStateNormal];
//            [_qingJieJiSeletedBtn setImage:seletedimage forState:UIControlStateSelected];
//            [_qingJieJiSeletedBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
//           
//            
//            return cell;
//
//        }
       
    if (indexPath.section ==0)
    {
        static NSString *cellIdentifier = @"beizhu";
        
        NSString *beizhu =@"";
        if (self.markContent.length==0) {
            beizhu = @"(选填)";
        }else{
            beizhu = self.markContent;
        }
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _marklabel = [[UILabel alloc]initWithFrame:CGRectMake(VIEW_WIDTH/3, 0, VIEW_WIDTH/2, 44)];
            [cell.contentView addSubview:_marklabel];
                   }
        _marklabel.textAlignment =NSTextAlignmentRight;
        _marklabel.font = [UIFont systemFontOfSize:15];
        _marklabel.textColor=[UIColor colorWithHexString:@"#999999"];
        _marklabel.text=beizhu;
        cell.textLabel.text=@"备注：";
        cell.textLabel.numberOfLines=1;
        cell.textLabel.font=[UIFont systemFontOfSize:15];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        [cell.layer setBorderWidth:0.7];
        [cell.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
        return cell;
    }
        }
    static NSString *cellIdentifier = @"cellIdentifier";
    SureOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[SureOrderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (self.orderType==kserviceSureorder) {
        [cell.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
        [cell.layer setBorderWidth:0.7];
    }
    NSDictionary *dataDic = [self.dataSource objectAtIndex:indexPath.row];
    [cell updateData:dataDic hoemMakeType:self.homeMakeType];
    return cell;
}

#pragma mark --UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.orderType==kserviceSureorder) {

        if (indexPath.section ==0) {
            UserCenter_FeedbackAndSuggestionController *addRemarksVC = [[UserCenter_FeedbackAndSuggestionController alloc]init];
            addRemarksVC.feedbackOrRemarksType = kRemarksType;
            [self.navigationController pushViewController:addRemarksVC animated:YES];
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.orderType == kproductSureOrder) {
        return 44;
    }
    if (section ==0) {
        return 0;
    }
    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
        if (self.orderType == kserviceSureorder) {
        return 0;
        }
      return 49;

}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 49)];
    bottomView.backgroundColor = [UIColor clearColor];
    return bottomView;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.orderType == kproductSureOrder) {
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 43)];
        titleView.backgroundColor = [UIColor whiteColor];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, CGRectGetWidth(self.view.bounds) - 30, 44)];
        titleLabel.text = @"大实惠云超市";
        titleLabel.font = [UIFont systemFontOfSize:15];
        [titleView addSubview:titleLabel];
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15, 43, CGRectGetWidth(titleLabel.bounds) + 15, 0.6)];
        UIImage *sepLineImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#dddddd"] frame:CGRectMake(0, 0, CGRectGetWidth(titleLabel.bounds) + 15, 0.6)];
        imageView.image = sepLineImage;
        [titleView addSubview:imageView];
        return titleView;

    }
    return nil;
}
#pragma mark -- SureOrderHeaderViewDelegate
- (void)selectXiaoqu {
    
}
- (void)selectDetailAddress {
    [self loadXiaoQuDetailInfoData];
}
- (void)modifiedAddress {
    ManageReceivedAddressController *manageReceivedAddressVC = [[ManageReceivedAddressController alloc]init];
    manageReceivedAddressVC.supperControllerType = kSureOrderPushToManageReceivedAddressController;
    [self.navigationController pushViewController:manageReceivedAddressVC animated:YES];
}
- (void)addMarkInfo {
    UserCenter_FeedbackAndSuggestionController *addRemarksVC = [[UserCenter_FeedbackAndSuggestionController alloc]init];
    addRemarksVC.feedbackOrRemarksType = kRemarksType;
    [self.navigationController pushViewController:addRemarksVC animated:YES];
    
}
- (void)selectServiceTime {
    SelectServiceTimeController *selectServiceTimeVC = [[SelectServiceTimeController alloc]init];
    [self.navigationController pushViewController:selectServiceTimeVC animated:YES];
}
//#pragma mark -- LouCengPickerViewDelegate
//- (void)selectedLouNumberModel:(LouCengInfoModel*)louNumberModel danYuanNumberModel:(LouCengInfoModel*)danyuanNumberModel roomNumberModel:(LouCengInfoModel*)roomNumberModel {
//    _headerView.detailAddressBtn.enabled = YES;
////    [self.louCengInfoArr addObject:louNumberModel];
////    [self.louCengInfoArr addObject:danyuanNumberModel];
////    [self.louCengInfoArr addObject:roomNumberModel];
//    NSString *louInfoStr = [NSString stringWithFormat:@"%@%@%@",louNumberModel.name,danyuanNumberModel.name,roomNumberModel.name];
//    [_headerView setDetailAddressTitle:louInfoStr];
//    
//}

#pragma mark -- button Action
- (void)submitOrderEvent:(id)sender {
    
    if (_totalPrice.floatValue > 33333) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"改账号为测试账号，支付价格需小于0.05元，才能正常支付" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
    } else {
        if (_isHadDefaultReceivedAddress) {
            if (self.orderType == kserviceSureorder) {
                if (self.serviceTime.length == 0) {
                    [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"请选择服务时间" inView:self.view];
                    return ;
                }
            }
            if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
                [self loadSubmitOrderData];
            }
            
        } else {
            if (_headerView.userNameTextField.text.length == 0) {
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"联系人姓名不能为空" inView:self.view];
                return;
            } else if (_headerView.userTelePhoneTextField.text.length == 0) {
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"联系人电话不能为空" inView:self.view];
                return ;
            } else if (_headerView.userAddressTextField.text.length ==0){
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"请填写详细地址" inView:self.view];
                return;
            } else {
                if (self.orderType == kserviceSureorder) {
                    if (self.serviceTime.length == 0) {
                        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"请选择服务时间" inView:self.view];
                        return ;
                    }
                }
                if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
                    [self loadSubmitOrderData];
                }
                
            }
        }
    }
    
}
- (void)backBtnAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- 初始化视图
- (void)setupSubview{
    CGFloat headerHight = 0;
    if (self.orderType == kproductSureOrder) {
         headerHight = _isHadDefaultReceivedAddress ? khadAddressHeight : knoAddressHeight;
    } else if (self.orderType == kserviceSureorder){
         headerHight = _isHadDefaultReceivedAddress ? khadAddressServiceheaderHight : knoAddressServiceHeaderHight;
    }
    _headerView = [[SureOrderHeaderView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), headerHight) hadOrdersAddressStatus:_isHadDefaultReceivedAddress withSureOrderType:self.orderType == kserviceSureorder ? kserviceSureorderHeader : kproductSureOrderHeader];
    _headerView.delegate = (id<SureOrderHeaderViewDelegate>)self;
    
    SureOrderFooterView *footView = [[SureOrderFooterView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), knoYouHuiHeight) isNewUser:NO isHadYouHui:YES isHideYouHuiShuoMing:YES];
    footView.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0
                                                              , 0
                                                              , CGRectGetWidth(self.view.bounds)
                                                              , CGRectGetHeight(self.view.bounds)-49)
                                             style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.tableHeaderView = _headerView;
//    _tableView.tableFooterView = footView;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    //底部视图
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMinX(_tableView.frame)
                                                           , CGRectGetHeight(self.view.bounds) - 49
                                                           , CGRectGetWidth(self.tableView.bounds)
                                                           , 49)];
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.85;
    [self.view addSubview:view];
    
    UIView *bottomView = [[UIView alloc]initWithFrame:view.frame];
    bottomView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bottomView];
    
    //总价
    UILabel *totalPriceTitle = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 55, 49)];
    totalPriceTitle.text = @"总计：";
    totalPriceTitle.backgroundColor = [UIColor clearColor];
    totalPriceTitle.font = [UIFont systemFontOfSize:15];
    totalPriceTitle.textColor = [UIColor whiteColor];
    totalPriceTitle.textAlignment = NSTextAlignmentCenter;
    [bottomView addSubview:totalPriceTitle];
    
    _totalPriceLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(totalPriceTitle.frame)
                                                           , CGRectGetMinY(totalPriceTitle.frame)
                                                           , 120
                                                           , CGRectGetHeight(totalPriceTitle.bounds))];
    _totalPriceLabel.font = [UIFont systemFontOfSize:18];
    _totalPriceLabel.textColor = [UIColor whiteColor];
    _totalPriceLabel.textAlignment = NSTextAlignmentLeft;
    _totalPriceLabel.text = [NSString stringWithFormat:@"￥%@",_totalPrice];
    _totalPriceLabel.backgroundColor = [UIColor clearColor];
    [bottomView addSubview:_totalPriceLabel];
    
    //提交订单
    UIImage *backGroundImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"de4d47"] frame:CGRectMake(0, 0, 100, 49)];
    _submitOrder = [UIButton buttonWithType:UIButtonTypeCustom];
    _submitOrder.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 100
                                    , CGRectGetMinY(_totalPriceLabel.frame)
                                    , 100
                                    , CGRectGetHeight(_totalPriceLabel.bounds));
    [_submitOrder setTitle:@"提交订单" forState:UIControlStateNormal];
    [_submitOrder setBackgroundImage:backGroundImage forState:UIControlStateNormal];
    [_submitOrder addTarget:self action:@selector(submitOrderEvent:) forControlEvents:UIControlEventTouchUpInside];
    _submitOrder.titleLabel.font = [UIFont systemFontOfSize:15];
    [bottomView addSubview:_submitOrder];
}

- (void)setServiceDataSource:(NSMutableArray *)serviceDataSource {
    _serviceDataSource = serviceDataSource;
}
-(NSMutableArray *)serviceDataSource {
    if (!_serviceDataSource) {
        _serviceDataSource = [[NSMutableArray alloc]init];
    }
    return _serviceDataSource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
